/**
 * 销售机会管理页面交互逻辑
 * 遵循Apple设计语言的交互原则
 */

class OpportunityManagement {
    constructor() {
        this.currentView = 'table'; // 当前视图模式：table 或 kanban
        this.currentPage = 1;
        this.pageSize = 20;
        this.totalRecords = 320;
        this.sortConfig = {
            field: null,
            direction: 'asc'
        };
        this.filters = {
            search: '',
            level: '',
            stage: '',
            consultant: '',
            time: ''
        };
        
        this.init();
    }

    init() {
        this.bindEvents();
        this.initializeData();
        this.updateDisplay();
    }

    bindEvents() {
        // 搜索功能
        this.bindSearchEvents();
        
        // 筛选器
        this.bindFilterEvents();
        
        // 视图切换
        this.bindViewEvents();
        
        // 表格交互
        this.bindTableEvents();
        
        // 分页
        this.bindPaginationEvents();
        
        // 操作按钮
        this.bindActionEvents();
        
        // 模态框
        this.bindModalEvents();
    }

    // ==================== 搜索功能 ====================
    bindSearchEvents() {
        const searchInput = document.getElementById('search-input');
        const searchClear = document.getElementById('search-clear');
        
        // 搜索输入
        searchInput?.addEventListener('input', (e) => {
            this.filters.search = e.target.value;
            this.debounceSearch();
        });
        
        // 清除搜索
        searchClear?.addEventListener('click', () => {
            searchInput.value = '';
            this.filters.search = '';
            this.applyFilters();
        });
        
        // 回车搜索
        searchInput?.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.applyFilters();
            }
        });
    }

    debounceSearch() {
        clearTimeout(this.searchTimeout);
        this.searchTimeout = setTimeout(() => {
            this.applyFilters();
        }, 500);
    }

    // ==================== 筛选器功能 ====================
    bindFilterEvents() {
        const filterElements = [
            'level-filter',
            'stage-filter', 
            'consultant-filter',
            'time-filter'
        ];
        
        filterElements.forEach(id => {
            const element = document.getElementById(id);
            element?.addEventListener('change', (e) => {
                const filterKey = id.replace('-filter', '');
                this.filters[filterKey] = e.target.value;
                this.applyFilters();
            });
        });
        
        // 重置筛选器
        document.getElementById('reset-filters')?.addEventListener('click', () => {
            this.resetFilters();
        });
    }

    resetFilters() {
        this.filters = {
            search: '',
            level: '',
            stage: '',
            consultant: '',
            time: ''
        };
        
        // 重置表单
        document.getElementById('search-input').value = '';
        document.getElementById('level-filter').value = '';
        document.getElementById('stage-filter').value = '';
        document.getElementById('consultant-filter').value = '';
        document.getElementById('time-filter').value = '';
        
        this.applyFilters();
    }

    applyFilters() {
        this.currentPage = 1;
        this.loadOpportunities();
        this.updatePagination();
    }

    // ==================== 视图切换 ====================
    bindViewEvents() {
        const viewButtons = document.querySelectorAll('.view-btn');
        
        viewButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                const view = e.currentTarget.dataset.view;
                this.switchView(view);
            });
        });
    }

    switchView(view) {
        this.currentView = view;
        
        // 更新按钮状态
        document.querySelectorAll('.view-btn').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.view === view);
        });
        
        // 切换视图显示
        document.getElementById('table-view').style.display = 
            view === 'table' ? 'block' : 'none';
        document.getElementById('kanban-view').style.display = 
            view === 'kanban' ? 'block' : 'none';
        
        if (view === 'kanban') {
            this.initKanbanView();
        }
    }

    // ==================== 表格交互 ====================
    bindTableEvents() {
        // 排序功能
        const sortableHeaders = document.querySelectorAll('.sortable');
        sortableHeaders.forEach(header => {
            header.addEventListener('click', (e) => {
                const field = e.currentTarget.dataset.sort;
                this.handleSort(field);
            });
        });
        
        // 行点击
        this.bindRowClickEvents();
    }

    bindRowClickEvents() {
        const tableBody = document.getElementById('opportunity-table-body');
        tableBody?.addEventListener('click', (e) => {
            const row = e.target.closest('.opportunity-row');
            if (row && !e.target.closest('.actions')) {
                const opportunityId = row.dataset.opportunityId;
                this.viewOpportunityDetail(opportunityId);
            }
        });
    }

    handleSort(field) {
        if (this.sortConfig.field === field) {
            this.sortConfig.direction = 
                this.sortConfig.direction === 'asc' ? 'desc' : 'asc';
        } else {
            this.sortConfig.field = field;
            this.sortConfig.direction = 'asc';
        }
        
        this.updateSortIcons();
        this.loadOpportunities();
    }

    updateSortIcons() {
        document.querySelectorAll('.sortable .fas').forEach(icon => {
            icon.className = 'fas fa-sort';
        });
        
        if (this.sortConfig.field) {
            const activeHeader = document.querySelector(
                `[data-sort="${this.sortConfig.field}"] .fas`
            );
            if (activeHeader) {
                activeHeader.className = 
                    this.sortConfig.direction === 'asc' 
                        ? 'fas fa-sort-up' 
                        : 'fas fa-sort-down';
            }
        }
    }

    // ==================== 分页功能 ====================
    bindPaginationEvents() {
        // 页码按钮
        document.querySelector('.pagination')?.addEventListener('click', (e) => {
            if (e.target.classList.contains('page-btn') && !e.target.disabled) {
                const pageNum = parseInt(e.target.textContent);
                if (!isNaN(pageNum)) {
                    this.goToPage(pageNum);
                }
            }
        });
        
        // 每页数量
        document.getElementById('page-size')?.addEventListener('change', (e) => {
            this.pageSize = parseInt(e.target.value);
            this.currentPage = 1;
            this.loadOpportunities();
            this.updatePagination();
        });
    }

    goToPage(pageNum) {
        const totalPages = Math.ceil(this.totalRecords / this.pageSize);
        if (pageNum >= 1 && pageNum <= totalPages) {
            this.currentPage = pageNum;
            this.loadOpportunities();
            this.updatePagination();
        }
    }

    updatePagination() {
        const totalPages = Math.ceil(this.totalRecords / this.pageSize);
        const startRecord = (this.currentPage - 1) * this.pageSize + 1;
        const endRecord = Math.min(this.currentPage * this.pageSize, this.totalRecords);
        
        // 更新信息显示
        const infoElement = document.querySelector('.pagination-info');
        if (infoElement) {
            infoElement.textContent = 
                `显示第 ${startRecord}-${endRecord} 条，共 ${this.totalRecords} 条记录`;
        }
        
        // 更新页码按钮
        this.renderPaginationButtons(totalPages);
    }

    renderPaginationButtons(totalPages) {
        const pagination = document.querySelector('.pagination');
        if (!pagination) return;
        
        let html = '';
        
        // 上一页
        html += `<button class="page-btn" ${this.currentPage === 1 ? 'disabled' : ''} 
                 onclick="opportunityManager.goToPage(${this.currentPage - 1})">
                 <i class="fas fa-chevron-left"></i></button>`;
        
        // 页码按钮
        const { start, end } = this.calculatePageRange(totalPages);
        
        if (start > 1) {
            html += `<button class="page-btn" onclick="opportunityManager.goToPage(1)">1</button>`;
            if (start > 2) {
                html += `<span class="page-dots">...</span>`;
            }
        }
        
        for (let i = start; i <= end; i++) {
            html += `<button class="page-btn ${i === this.currentPage ? 'active' : ''}" 
                     onclick="opportunityManager.goToPage(${i})">${i}</button>`;
        }
        
        if (end < totalPages) {
            if (end < totalPages - 1) {
                html += `<span class="page-dots">...</span>`;
            }
            html += `<button class="page-btn" onclick="opportunityManager.goToPage(${totalPages})">${totalPages}</button>`;
        }
        
        // 下一页
        html += `<button class="page-btn" ${this.currentPage === totalPages ? 'disabled' : ''} 
                 onclick="opportunityManager.goToPage(${this.currentPage + 1})">
                 <i class="fas fa-chevron-right"></i></button>`;
        
        pagination.innerHTML = html;
    }

    calculatePageRange(totalPages) {
        const delta = 2;
        const start = Math.max(1, this.currentPage - delta);
        const end = Math.min(totalPages, this.currentPage + delta);
        return { start, end };
    }

    // ==================== 操作按钮 ====================
    bindActionEvents() {
        // 新增机会
        document.getElementById('add-opportunity-btn')?.addEventListener('click', () => {
            window.location.href = 'opportunity-form.html';
        });
        
        // 导入
        document.getElementById('import-btn')?.addEventListener('click', () => {
            this.showImportModal();
        });
        
        // 导出
        document.getElementById('export-btn')?.addEventListener('click', () => {
            this.exportOpportunities();
        });
        
        // 漏斗期间选择
        document.getElementById('funnel-period')?.addEventListener('change', (e) => {
            this.updateFunnelData(e.target.value);
        });
    }

    // ==================== 数据加载 ====================
    initializeData() {
        this.loadOpportunities();
        this.loadFunnelData();
        this.loadStatsData();
    }

    loadOpportunities() {
        // 模拟API请求
        setTimeout(() => {
            this.renderOpportunityTable();
            this.updateResultCount();
        }, 300);
    }

    renderOpportunityTable() {
        const tableBody = document.getElementById('opportunity-table-body');
        if (!tableBody) return;
        
        // 模拟数据
        const opportunities = this.getMockOpportunities();
        
        let html = '';
        opportunities.forEach(opp => {
            html += this.generateOpportunityRow(opp);
        });
        
        tableBody.innerHTML = html;
        this.bindRowClickEvents();
    }

    generateOpportunityRow(opp) {
        return `
            <tr class="opportunity-row" data-opportunity-id="${opp.id}">
                <td class="opportunity-number">${opp.number}</td>
                <td class="opportunity-name">
                    <div class="opportunity-info">
                        <div class="name">${opp.name}</div>
                        <div class="customer-link">
                            <a href="customer-detail.html?id=${opp.customerId}" class="link-text">
                                <i class="fas fa-external-link-alt"></i>
                                查看客户
                            </a>
                        </div>
                    </div>
                </td>
                <td class="customer-info">
                    <div class="customer-details">
                        <div class="customer-name">${opp.customerName}</div>
                        <div class="customer-phone">${opp.customerPhone}</div>
                    </div>
                </td>
                <td>
                    <span class="level-badge level-${opp.level.toLowerCase()}">${opp.level}级</span>
                </td>
                <td>
                    <div class="stage-info">
                        <span class="stage-badge stage-${opp.stageNumber}">${opp.stageName}</span>
                        <div class="stage-progress-mini">
                            <div class="progress-line" style="width: ${opp.progress}%"></div>
                        </div>
                    </div>
                </td>
                <td class="amount">¥${opp.amount.toLocaleString()}</td>
                <td class="date">${opp.expectedCloseDate}</td>
                <td class="consultant">${opp.consultant}</td>
                <td class="date">${opp.createdDate}</td>
                <td class="actions">
                    <div class="action-buttons">
                        <button class="action-btn" title="查看详情" onclick="opportunityManager.viewOpportunity(${opp.id})">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="action-btn" title="编辑" onclick="opportunityManager.editOpportunity(${opp.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="action-btn" title="推进阶段" onclick="opportunityManager.advanceStage(${opp.id})">
                            <i class="fas fa-step-forward"></i>
                        </button>
                        <button class="action-btn" title="更多操作" onclick="opportunityManager.showMoreActions(${opp.id})">
                            <i class="fas fa-ellipsis-h"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    }

    getMockOpportunities() {
        // 模拟数据，实际应从API获取
        return [
            {
                id: 1,
                number: 'OPP20250121001',
                name: '李女士夫妇-云南深度7日游',
                customerName: '李大妈',
                customerPhone: '139****8002',
                customerId: 101,
                level: 'A',
                stageNumber: 5,
                stageName: '决策促成',
                progress: 83,
                amount: 15800,
                expectedCloseDate: '2025-01-25',
                consultant: '张顾问',
                createdDate: '2025-01-18'
            },
            {
                id: 2,
                number: 'OPP20250120002',
                name: '王先生家庭-海南度假5日游',
                customerName: '王先生',
                customerPhone: '137****8003',
                customerId: 102,
                level: 'B',
                stageNumber: 3,
                stageName: '方案推荐',
                progress: 50,
                amount: 12600,
                expectedCloseDate: '2025-01-28',
                consultant: '李顾问',
                createdDate: '2025-01-19'
            },
            {
                id: 3,
                number: 'OPP20250119003',
                name: '陈阿姨-桂林山水3日游',
                customerName: '陈阿姨',
                customerPhone: '138****8004',
                customerId: 103,
                level: 'C',
                stageNumber: 2,
                stageName: '需求分析',
                progress: 33,
                amount: 3200,
                expectedCloseDate: '2025-02-05',
                consultant: '王顾问',
                createdDate: '2025-01-17'
            }
        ];
    }

    updateResultCount() {
        const countElement = document.querySelector('.result-count');
        if (countElement) {
            countElement.textContent = `共 ${this.totalRecords} 条记录`;
        }
    }

    // ==================== 看板视图 ====================
    initKanbanView() {
        // 初始化看板数据
        this.loadKanbanData();
        this.enableKanbanDragDrop();
    }

    loadKanbanData() {
        const kanbanBoard = document.querySelector('.kanban-board');
        if (!kanbanBoard) return;
        
        // 这里可以根据当前数据重新渲染看板
        console.log('Loading kanban data...');
    }

    enableKanbanDragDrop() {
        const cards = document.querySelectorAll('.kanban-card');
        const columns = document.querySelectorAll('.kanban-cards');
        
        cards.forEach(card => {
            card.draggable = true;
            card.addEventListener('dragstart', this.handleDragStart.bind(this));
            card.addEventListener('dragend', this.handleDragEnd.bind(this));
        });
        
        columns.forEach(column => {
            column.addEventListener('dragover', this.handleDragOver.bind(this));
            column.addEventListener('drop', this.handleDrop.bind(this));
        });
    }

    handleDragStart(e) {
        e.dataTransfer.setData('text/plain', e.target.dataset.opportunityId);
        e.target.style.opacity = '0.5';
    }

    handleDragEnd(e) {
        e.target.style.opacity = '1';
    }

    handleDragOver(e) {
        e.preventDefault();
    }

    handleDrop(e) {
        e.preventDefault();
        const opportunityId = e.dataTransfer.getData('text/plain');
        const newStage = e.target.closest('.kanban-column').dataset.stage;
        
        this.moveOpportunityToStage(opportunityId, newStage);
    }

    moveOpportunityToStage(opportunityId, newStage) {
        // 实际项目中这里会调用API更新阶段
        console.log(`Moving opportunity ${opportunityId} to stage ${newStage}`);
        
        // 更新UI
        this.showNotification('机会阶段已更新', 'success');
    }

    // ==================== 模态框管理 ====================
    bindModalEvents() {
        // 操作菜单
        this.bindActionMenuEvents();
        
        // 阶段推进
        this.bindAdvanceStageEvents();
    }

    bindActionMenuEvents() {
        const modal = document.getElementById('action-menu-modal');
        
        // 点击遮罩关闭
        modal?.addEventListener('click', (e) => {
            if (e.target === modal) {
                this.closeActionMenu();
            }
        });
    }

    bindAdvanceStageEvents() {
        const modal = document.getElementById('advance-stage-modal');
        
        // 点击遮罩关闭
        modal?.addEventListener('click', (e) => {
            if (e.target === modal) {
                this.closeAdvanceModal();
            }
        });
    }

    // ==================== 具体操作方法 ====================
    viewOpportunity(id) {
        window.location.href = `opportunity-detail.html?id=${id}`;
    }

    editOpportunity(id) {
        window.location.href = `opportunity-form.html?id=${id}`;
    }

    viewOpportunityDetail(id) {
        this.viewOpportunity(id);
    }

    advanceStage(id) {
        this.showAdvanceStageModal(id);
    }

    showMoreActions(id) {
        this.currentOpportunityId = id;
        this.showActionMenu();
    }

    showActionMenu() {
        const modal = document.getElementById('action-menu-modal');
        if (modal) {
            modal.style.display = 'flex';
            setTimeout(() => modal.classList.add('show'), 10);
        }
    }

    closeActionMenu() {
        const modal = document.getElementById('action-menu-modal');
        if (modal) {
            modal.classList.remove('show');
            setTimeout(() => modal.style.display = 'none', 300);
        }
    }

    showAdvanceStageModal(id) {
        this.currentOpportunityId = id;
        const modal = document.getElementById('advance-stage-modal');
        if (modal) {
            modal.style.display = 'flex';
            setTimeout(() => modal.classList.add('show'), 10);
        }
    }

    closeAdvanceModal() {
        const modal = document.getElementById('advance-stage-modal');
        if (modal) {
            modal.classList.remove('show');
            setTimeout(() => modal.style.display = 'none', 300);
        }
    }

    confirmAdvanceStage() {
        // 实际项目中这里会调用API
        console.log(`Advancing stage for opportunity ${this.currentOpportunityId}`);
        
        this.closeAdvanceModal();
        this.showNotification('销售阶段已推进', 'success');
        this.loadOpportunities();
    }

    // ==================== 数据统计 ====================
    loadFunnelData() {
        // 模拟加载漏斗数据
        this.updateFunnelDisplay();
    }

    loadStatsData() {
        // 模拟加载统计数据
        this.updateStatsDisplay();
    }

    updateFunnelData(period) {
        console.log(`Updating funnel data for period: ${period}`);
        // 这里根据时间段重新加载数据
        this.loadFunnelData();
    }

    updateFunnelDisplay() {
        // 更新漏斗显示数据，实际项目中从API获取
        console.log('Updating funnel display...');
    }

    updateStatsDisplay() {
        // 更新统计卡片显示，实际项目中从API获取
        console.log('Updating stats display...');
    }

    // ==================== 工具方法 ====================
    showNotification(message, type = 'info') {
        // 显示通知消息
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.classList.add('show');
        }, 10);
        
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }

    exportOpportunities() {
        // 导出功能
        console.log('Exporting opportunities...');
        this.showNotification('正在导出数据...', 'info');
    }

    showImportModal() {
        // 显示导入模态框
        console.log('Showing import modal...');
    }

    updateDisplay() {
        this.loadOpportunities();
        this.updatePagination();
    }
}

// ==================== 全局函数 ====================
function viewOpportunity(id) {
    window.opportunityManager.viewOpportunity(id);
}

function editOpportunity(id) {
    window.opportunityManager.editOpportunity(id);
}

function advanceStage(id) {
    window.opportunityManager.advanceStage(id);
}

function showMoreActions(id) {
    window.opportunityManager.showMoreActions(id);
}

function closeActionMenu() {
    window.opportunityManager.closeActionMenu();
}

function closeAdvanceModal() {
    window.opportunityManager.closeAdvanceModal();
}

function confirmAdvanceStage() {
    window.opportunityManager.confirmAdvanceStage();
}

function addFollowup() {
    console.log('Adding followup...');
    closeActionMenu();
}

function scheduleCallback() {
    console.log('Scheduling callback...');
    closeActionMenu();
}

function sendProposal() {
    console.log('Sending proposal...');
    closeActionMenu();
}

function viewHistory() {
    console.log('Viewing history...');
    closeActionMenu();
}

function transferOpportunity() {
    console.log('Transferring opportunity...');
    closeActionMenu();
}

function deleteOpportunity() {
    if (confirm('确定要删除这个销售机会吗？')) {
        console.log('Deleting opportunity...');
        window.opportunityManager.showNotification('销售机会已删除', 'success');
    }
    closeActionMenu();
}

// ==================== 初始化 ====================
document.addEventListener('DOMContentLoaded', () => {
    window.opportunityManager = new OpportunityManagement();
});